package com.example.qsindusty.jmm_spline.LoginActivity;


import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;

import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.R;
import com.example.qsindusty.jmm_spline.Unallcation.AllcationFragment;
import com.example.qsindusty.jmm_spline.Unallcation.UnAllcationFragment;

import com.example.qsindusty.jmm_spline.eventMessage.MessageEvent;
import com.example.qsindusty.jmm_spline.recombinationfragment.RecombibationFragment;
import com.google.gson.Gson;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.LoadingDialogUtils;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.StatusBarUtil;
import com.yixin.ystartlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.options.RegisterOptionalUserInfo;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends AppCompatActivity implements LoginContract.View {
    @BindView(R.id.user_count)
    TextInputEditText userCount;
    @BindView(R.id.user_password)
    TextInputEditText userPassword;
    @BindView(R.id.login_bt)
    Button loginBt;
    @BindView(R.id.register)
    TextView register;
   /* @BindView(R.id.service)
    EditText service;
    @BindView(R.id.servicehint)
    TextView servicehint;*/

    private LoginPresenter mPerenter;
    public static int MAIN_REGISTESER_CODE = 102;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        StatusBarUtil.immersive(this.getWindow());

    }

    @Override
    protected void onStart() {
        super.onStart();
        bindPresenter();
        initview();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindPresenter();
    }

    AlertDialog alertDialog;

    @Override
    public void showLoading() {
        alertDialog = LoadingDialogUtils.create(this, "登陆");
        alertDialog.show();

    }

    @Override
    public void closeLoading() {
        if (alertDialog != null && alertDialog.isShowing())
            alertDialog.dismiss();
    }

    @Override
    public void bindPresenter() {
        if (mPerenter == null) {
            mPerenter = new LoginPresenter();
        }
        mPerenter.bindView(this);
    }

    @Override
    public void unbindPresenter() {
        mPerenter.unbindView();
    }


    private void initview() {
        String userCounts = GeneralPreferencesUtils.getSharedPreference(this, Config.usercount, null);
        String userpsw = GeneralPreferencesUtils.getSharedPreference(this, Config.userpsw, null);
        if (!TextUtils.isEmpty(userCounts)) {
            userCount.setText(userCounts);
        }
        if (!TextUtils.isEmpty(userpsw)) {
            userPassword.setText(userpsw);
        }
         //   service.setText(Config.URL_JMMURL);
    }

    @Override
    public void Login() {
        LogUtils.d("name：" + userCount.getText().toString().trim());
        LogUtils.d("password：" + userPassword.getText().toString().trim());
        if (TextUtils.isEmpty(userCount.getText().toString().trim())) {
            ToastUtils.showLongToast(this, "请输入账号");
            return;
        }
        if (TextUtils.isEmpty(userPassword.getText().toString().trim())) {
            ToastUtils.showLongToast(this, "请输入密码");
            return;
        }
       /* if (TextUtils.isEmpty(service.getText().toString().trim())){
            Config.URL_JMMURL="http://192.168.3.29:8090/jmm/";
        }else{
            Config.URL_JMMURL=service.getText().toString().trim();
        }*/
        mPerenter.Login(userCount.getText().toString().trim(), userPassword.getText().toString().trim(), LoginActivity.this);
    }

    @Override
    public void refresshDataSuccessful(final LoginData data, String username, String userpsw) {
        final Gson gson = new Gson();

        UnAllcationFragment.isFresh = true;
        AllcationFragment.isFresh = true;
        RecombibationFragment.isFresh = true;
        LogUtils.e("token=" + GeneralPreferencesUtils.getSharedPreference(getApplicationContext(), Config.ISFIRST, null));
        GeneralPreferencesUtils.setSharedPreference(this, Config.token, data.getData().getTOKEN());
        GeneralPreferencesUtils.setSharedPreference(this, Config.usercount, username);
        GeneralPreferencesUtils.setSharedPreference(this, Config.userpsw, userpsw);
        Observable.just(data).subscribeOn(Schedulers.io())
                .subscribe(new Consumer<LoginData>() {
                    @Override
                    public void accept(LoginData loginData) throws Exception {
                        GeneralPreferencesUtils.setSharedPreference(getApplicationContext(), Config.userinfo, gson.toJson(data));
                        if (GeneralPreferencesUtils.getSharedPreference(getApplicationContext(), Config.ISFIRST, false)) {
                            Set<String> set = new HashSet<>();
                            set.add(loginData.getData().getTOKEN());
                            JPushMessage jPushMessage = new JPushMessage();
                            int sequence = jPushMessage.getSequence();
                            JPushInterface.setTags(getApplicationContext(), sequence, set);
                            GeneralPreferencesUtils.setSharedPreference(getApplicationContext(), Config.ISFIRST, false);

                        }
                    }
                });
        JMessageClient.login(data.getData().getTAG(), Config.Jm_Password, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                LogUtils.i("i=="+i+"s="+s);
                if (i==0){
                    GeneralPreferencesUtils.setSharedPreference(LoginActivity.this,Config.tag,
                            data.getData().getTAG());
                    EventBus.getDefault().post(new MessageEvent(Config.CHAT_COVREFURESH));
                    finish();
                }
                else if (i==801003){
                    RegisterOptionalUserInfo info = new RegisterOptionalUserInfo();
                    info.setNickname(data.getData().getYHMC());
                    JMessageClient.register(data.getData().getTAG(), Config.Jm_Password, info
                            , new BasicCallback() {
                                @Override
                                public void gotResult(int i, String s) {
                                    if (i==0){

                                        finish();
                                    }
                                }
                            });
                }
            }
        });


        finish();
    }

    @Override
    public void refreshDataFraier(String msg) {
        ToastUtils.showLongToast(this, "登陆失败");
    }

    @OnClick(R.id.login_bt)
    public void onViewClicked() {
        LogUtils.i("onclick");
        Login();
    }


    @Override
    public void onBackPressed() {

    }
}

